<template>
  <div class="serve-back-node">
    <el-form label-position="left" :rules="rules" label-width="418px" :model="formData" ref='nodeForm' hide-required-asterisk>
      <div class="service-title">
        <span>设置具体服务的恢复策略</span>
      </div>
      <transition-group name="drag" class="service-list" tag="div" key="drag">
        <div v-for="(item, index) in formData.serviceList" @dragenter="dragenter($event, index)" @dragover="dragover($event, index)" @dragstart="dragstart($event, index)" draggable :key="item.serviceKey" class="service-item">
          <div class="sort-bg"></div><!-- 原生拖拽svg支持度较低 此处用背景图代替 -->
          <el-form-item v-if="item.hasRefSignal" :label="`${index + 1}. ${item.serviceName}`" :prop="'serviceList.' + index + '.resetStrategy'" :rules="rules.resetStrategy">
            <el-select v-model="item.resetStrategy" placeholder="请选择" class="back-select">
              <el-option label="不恢复" value="noReset"></el-option>
              <el-option label="智能恢复" value="intelligentReset"></el-option>
              <el-option label="强制恢复" value="forceReset"></el-option>
            </el-select>
          </el-form-item>
          <div v-else class="can-not-reset">
            <div class="service-name">{{ index + 1 }}. {{ item.serviceName}}</div>
            <div class="service-tip">
              <span class="text"> 无法恢复 </span>
              <el-popover placement="bottom-end" width="200" trigger="hover" content="服务未在元模型中绑定信号，无法回退" class="input-description" popper-class='desc-poper'>
                <svg-icon slot="reference" icon-class="说明"/>
              </el-popover>
              </div>
          </div>
        </div>
      </transition-group>
    </el-form>
  </div>
</template>

<script>
import { deepClone } from '@/utils/helper/jsUtil'
import RuleNodeBaseClass from '@/components/ruleNode/RuleNodeBaseClass'
import { NodeType } from '@/model/node.model'
import { mapState } from 'vuex'
import { throttle } from 'lodash'

export default {
  name: 'AdvancedLibServeBackNode',
  mixins: [RuleNodeBaseClass],
  props: {
  },
  data() {
    return {
      dragIndex: '',
      formData: {
        serviceList: []
      },
      rules: {
        resetStrategy: [{ required: true, message: ' ', trigger: 'change' }]
      }
    }
  },
  mounted() {
  },
  methods: {
    initValue() {
      const initFormData = this.initialForm ? deepClone(this.initialForm) : {}
      Object.assign(this.formData, initFormData)
      this.formData.serviceList = this.formData.serviceList || []
      this.formData.serviceList = this.updateServer()
    },
    getFormData() {
      return deepClone(this.formData)
    },
    // 获取规则链所有服务并更新服务恢复列表
    updateServer() {
      const nodeList = this.graph.getNodes().map(item => item.getData())
      const serverNodeList = nodeList.filter(item => item.type === NodeType.serviceNode)
      const allServerList = []
      serverNodeList.forEach(item => item.configuration.serviceSequence && allServerList.push(...item.configuration.serviceSequence))
      const serverList = []
      // 去重
      allServerList.forEach(item => {
        if (!serverList.some(server => server.serviceKey === item.serviceKey)) {
          const { serviceKey, serviceName, metaModelId } = item
          const hasRefSignal = !!(item.inputParams?.length && item.inputParams.find(param => param.hasRefSignal))
          serverList.push({ serviceKey, serviceName, metaModelId, hasRefSignal, resetStrategy: '' })
        }
      })
      // 旧列表剔除已不存在的项目
      const targetList = []
      this.formData.serviceList.forEach(item => {
        const newItem = serverList.find(server => server.serviceKey === item.serviceKey)
        if (newItem) { targetList.push(item) }
      })
      // 新列表新增项赋值至旧列表
      serverList.forEach(item => {
        const oldItem = targetList.find(server => server.serviceKey === item.serviceKey)
        if (!oldItem) {
          targetList.push(item)
        }
      })
      return targetList
    },
    validateForm() {
      let isValid
      this.$refs.nodeForm.validate(valid => { isValid = valid })
      return isValid
    },
    shuffle() {
      this.formData.serviceList = this.$shuffle(this.formData.serviceList)
    },
    dragstart(e, index) {
      if (e.offsetX > 440) {
        e.preventDefault()
      } else {
        this.dragIndex = index
      }
    },
    dragenter: throttle(function(e, index) { this.setIndex(e, index) }, 200),
    setIndex(e, index) {
      e.preventDefault()
      // 避免源对象触发自身的dragenter事件
      if (this.dragIndex !== index) {
        const source = this.formData.serviceList[this.dragIndex]
        this.formData.serviceList.splice(this.dragIndex, 1)
        this.formData.serviceList.splice(index, 0, source)
        // 排序变化后目标对象的索引变成源对象的索引
        this.dragIndex = index
      }
    },
    dragover(e, index) {
      e.preventDefault()
    }
  },
  computed: {
    ...mapState({
      graph: state => state.graph.graph
    })
  }
}
</script>
<style lang="scss">
.serve-back-node {
  .service-title{
    margin-bottom: 8px;
    font-weight: bold;
  }
  .sort-bg{
    cursor: move;
    width: 44px;
    background: url();
    background-repeat: no-repeat;
    background-position: 15px center;
    padding: 0 15px;
  }
  .service-list{
    .service-item{
      padding: 8px;
      margin-bottom: 8px;
      background-color: #f2f3f5;
      display: flex;
      .el-form-item{
        margin-bottom: 0;
        // .el-form-item__label{
        //   cursor: move;
        // }
      }
      .can-not-reset{
        line-height: 32px;
        display: flex;
        .service-name{
          width: 418px;
        }
        .service-tip{
          color: #666;
          .text{
            color: #1F1F1F;
          }
        }
      }
    }
  }
  .drag-move {
    transition: transform .2s;
  }
}
</style>
